package com.balance.anole.erp.security.login.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.balance.anole.admin.to.LoginUserTO;
import com.balance.anole.admin.to.StaffInfoTO;
import com.balance.anole.erp.common.dao.hibernate.BaseDAOImpl;
import com.balance.anole.erp.security.login.dao.LoginUserDAO;

public class LoginUserDAOImpl extends BaseDAOImpl implements LoginUserDAO{

	@SuppressWarnings("unchecked")
	@Override
	public LoginUserTO getLoginUserTO(LoginUserTO loginUserTO) {
		LoginUserTO loginUser = null;
		if(loginUserTO != null){
			StaffInfoTO sample = loginUserTO.getStaffInfo();
			if(sample != null){
				String staffId = sample.getStaffId();
				StaffInfoTO staff = getStaffInfoTOByStaffId(staffId);
				if(staff != null){
					Integer id = staff.getId();
					DetachedCriteria dc = DetachedCriteria.forClass(LoginUserTO.class);
					dc.add(Restrictions.eq("id", id)).add(Restrictions.eq("password", loginUserTO.getPassword()));

					List<LoginUserTO> users = getHibernateTemplate().findByCriteria(dc);
					if(users != null && users.size() > 0){
						loginUser = users.get(0);
					}

				}
			}
		}
		return loginUser;
	}

	@SuppressWarnings("unchecked")
	@Override
	public StaffInfoTO getStaffInfoTOByStaffId(String staffId) {

		DetachedCriteria dc = DetachedCriteria.forClass(StaffInfoTO.class);
		dc.add(Restrictions.eq("staffId", staffId));

		/*String hql = "from com.balance.anole.admin.to.StaffInfoTO where staffId = :staffId";
		Query q = getSession().createQuery(hql);
		q.setParameter("staffId", staffId);
		List l = q.list();*/

		List l = getHibernateTemplate().findByCriteria(dc);
		if(l != null && l.size() > 0){
			return (StaffInfoTO)l.get(0);
		}
		return null;
	}
}
